<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;

use App\Models\GoodsType;
use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\GoodsTypeRequest;

use App\Models\Product\Types;
use App\Models\Product\TypesTranslation;

class GoodsTypeController extends AdminController
{
    /**
     * 产品类型列表
     * @return \Illuminate\Contracts\View\View
     */
    public function index()
    {
        /*
                $Types = new Types();


                $sid = DB::table('goods_type_translations')->max('sid');
                $Types->classname = "项目类别";
                $Types->online = 1;
                $Types->save();

                 foreach (config('translatable.locales') as $locale => $item) {
                    $Types->translateOrNew($locale)->title ="项目类别";
                    $Types->translateOrNew($locale)->pid = 0;
                    $Types->translateOrNew($locale)->sid = $sid+1;

                    $Types->translateOrNew($locale)->sort = 255;
                    $Types->translateOrNew($locale)->status = 1;
                    $Types->translateOrNew($locale)->body = 0;
                    $Types->translateOrNew($locale)->description = 0;
                    $Types->translateOrNew($locale)->thumb = 0;


                }
                 $Types->save();
                return 'yes';
        */

        return View::make('admin.goodstype.index');
    }

    /**
     * 数据接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {
        $pid = $request->pid ?? 0;
        $created_at = $request->created_at ?? null;
        $lang = $request->get('lang',app()->getLocale());
        $model = TypesTranslation::query();

        if ($lang) {
            $model = $model->where('locale', $lang);
        }
       // $model = $model->where('types_id', $pid);
        if (!empty($created_at)) {
            $startime = substr($created_at, 0, 20);
            $endtime = substr($created_at, -20, 20);
            $model = $model->whereBetween('created_at', [$startime, $endtime]);
        }
        $res = $model->get();
/*
->with(['children'=>function($q) use($lang){
            return $q->where('locale', $lang);
        }])

*/
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res->count(),
            'data' => $res
        ];
        return Response::json($data);
    }

    /**
     * 添加
     * @return \Illuminate\Contracts\View\View
     */
    public function create(Request $request)
    {

        $goodsCat = new TypesTranslation();
        $lang = $request->get('lang', app()->getLocale());
        $goodstype = TypesTranslation::with('children')->where('pid', 0)
            ->where('locale', $lang)->orderBy('sort', 'desc')->get();
        return View::make('admin.goodstype.create', compact('goodstype','goodsCat'));
    }

    /**
     * 添加
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(GoodsTypeRequest $request)
    {
        DB::beginTransaction();
        try {
            $Types = new Types();
            $sid = DB::table('goods_type_translations')->max('sid');
            $Types->classname = $request->title;
            $Types->online = 1;
            $Types->save();
            foreach (config('translatable.locales') as $locale => $item) {
                $Types->translateOrNew($locale)->title = $request->title;
                $Types->translateOrNew($locale)->pid = $request->get('pid');
                $Types->translateOrNew($locale)->sid = $sid + 1;
                $Types->translateOrNew($locale)->sort = 255;
                $Types->translateOrNew($locale)->status = 1;
                $Types->translateOrNew($locale)->description = $request->get('description') ?? null;
                $Types->translateOrNew($locale)->thumb = $request->thumb ?? '';
            }
            $Types->save();
            DB::commit();
            return Response::json(['code' => 0, 'msg' => '添加成功']);
        } catch (\Exception $exception) {
            DB::rollback();
        }
        return Response::json(['code' => 401, 'msg' => '添加失败']);
    }


    /**
     * 更新 View
     * @param $id
     * @return \Illuminate\Contracts\View\View
     */
    public function edit(Request $request)
    {
        $id = (int) $request->get('id');
        $lang = $request->get('lang', app()->getLocale());
        $goodstype = TypesTranslation::with('children')->where('pid', 0)
            ->where('locale', $lang)->orderBy('sort', 'desc')->get();
        $goodsCat = TypesTranslation::findOrFail($id);

        return View::make('admin.goodstype.edit', compact('goodsCat', 'goodstype'));
    }

    /**
     * 更新 DG
     * @param TagRequest $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function update(GoodsTypeRequest $request)
    {
        $id = (int)$request->id;
        $locale = $request->get('locale');

        $GoodsType = Types::whereTranslation('id', $id)->firstOrFail();
        $typeid = $GoodsType->types_id;
        $data = $request->all();
        $data = $request->except(['file', '_token','locale']);
        DB::beginTransaction();
        try {

            $group = Types::where('id',$typeid)->first();
            foreach (config('translatable.locales') as $locale => $item) {

                $group->translateOrNew($locale)->pid = $data['pid'];

            }
            $group->save();





            $GoodsType->translateOrNew($locale)->pid = $data['pid'];
            $GoodsType->translateOrNew($locale)->title = $data['title'];
            $GoodsType->translateOrNew($locale)->description = $data['description'] ?? '';
            $GoodsType->translateOrNew($locale)->thumb = $data['thumb'] ?? '';
            $GoodsType->translateOrNew($locale)->sort = $data['sort'] ?? 255;
            $GoodsType->translateOrNew($locale)->status = $data['status'];
            $GoodsType->save();
            DB::commit();
            return Response::json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $exception) {
            DB::rollback();
        }
        return Response::json(['code' => 401, 'msg' => '更新失败']);
    }

    /**
     * 删除标签
     * @param Request $request
     */
    public function destroy(Request $request)
    {

        $ids = $request->get('ids');
        $GoodsType = GoodsType::with(['childs', 'Product'])->find($ids[0]);
        if ($GoodsType == null) {
            return Response::json(['code' => 1, 'msg' => '产品类型不存在']);
        }
        if ($GoodsType->childs->isNotEmpty()) {
            return Response::json(['code' => 1, 'msg' => '该产品类型下有子分类，不能删除']);
        }
        if ($GoodsType->Product->isNotEmpty()) {
            return Response::json(['code' => 1, 'msg' => '该产品类型下有产品，不能删除']);
        }
        try {
            $GoodsType->delete();
            return Response::json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $exception) {
            return Response::json(['code' => 1, 'msg' => '删除失败']);
        }
    }
}
